package iot.servlet;

import iot.bean.ScriptNeedInfo;
import iot.bean.Tgatedevice;
import iot.bean.Thistorydata;
import iot.bean.Tuser;
import iot.dao.HistorydataDao;
import iot.dao.UtilsDao;
import iot.utils.CodeExchange;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.IOUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

@SuppressWarnings({ "serial", "unused" })
public class HistoryDataServlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public HistoryDataServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/text;charset=utf-8");
		response.setCharacterEncoding("UTF-8");
		String action = request.getParameter("action");
		if (action != null) 
		{
			if (action.equals("add")) {
				Thistorydata historydata = new Thistorydata();
				// 定义 UserDao（用户信息处理的 JavaBean），调用 add()方法实现用户信息添加
				HistorydataDao historydataDao = new HistorydataDao();
				InputStream is= null;
				is = request.getInputStream();
				String bodyInfo = IOUtils.toString(is, "UTF-8");
				System.out.println("Recv Data:" + bodyInfo);
				// 获取数据，存放到值 JavaBean user
				historydata.setRecorddata(CodeExchange.chinese(bodyInfo));
				historydata.setRemark(CodeExchange.chinese(request.getParameter("remark")));
				// 这里还可以进一步查询用户名是否存在，避免用户名重复
				PrintWriter out = response.getWriter();
				if (historydataDao.add(historydata)) {
					out.println("添加成功！");
				} else {
					out.println("添加失败！");
				}
				// 用户信息更新操作
				return;
			} 
			else if (action.equals("query")) {
				HistorydataDao historydataDao = new HistorydataDao();
				String starttime = CodeExchange.chinese(request.getParameter("starttime"));
				String endtime = CodeExchange.chinese(request.getParameter("endtime"));
				/*HistorydataDao historydataDao = new HistorydataDao();
				ArrayList<Thistorydata> historydataes = new ArrayList<Thistorydata>();*/
				//historydataes = historydataes.queryPage(whereSQL, Integer.parseInt(page));
				//String likeTag = CodeExchange.chinese(request.getParameter("likeTag"));
				String likeTag = "humi";
				ArrayList<Thistorydata> queryDatas;
				if(starttime==null|starttime.equals(""))
					queryDatas = historydataDao.query(likeTag);//这里的likeTag给个JSON中有的即可
				else
					queryDatas = historydataDao.query(starttime, endtime, likeTag);//这里的likeTag给个JSON中有的即可
				ArrayList<Integer> sendHumi = new ArrayList<Integer>();
				ArrayList<Integer> sendTemp = new ArrayList<Integer>();
				ArrayList<String> sendTime = new ArrayList<String>();
				if (queryDatas != null && queryDatas.size() > 0) {
					SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					for(int i = 0;i<queryDatas.size();i++) {
						JSONObject e = (JSONObject) JSONObject.parse(((Thistorydata)queryDatas.get(i)).getRecorddata());
						sendTime.add(sdf.format(((Thistorydata)queryDatas.get(i)).getRecordtime()));
						// 以下需要查表了解有那些数据
						sendHumi.add(Integer.parseInt(e.getString("humi")));
						sendTemp.add(Integer.parseInt(e.getString("temp")));
					}
				}
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("time", sendTime);
				map.put("humi", sendHumi);
				map.put("temp", sendTemp);
				String jsonStr = JSON.toJSONString(map);
				PrintWriter out = response.getWriter();
				out.println(jsonStr);
				return;
			}
			else if (action.equals("last")) {
				HistorydataDao historydataDao = new HistorydataDao();
				//String likeTag = CodeExchange.chinese(request.getParameter("likeTag"));
				String likeTag = "humi";
				Thistorydata lastDatas = new Thistorydata();
				lastDatas = historydataDao.last(likeTag);
				int sendHumi;
				int sendTemp;
				JSONObject e = (JSONObject) JSONObject.parse(((Thistorydata)lastDatas).getRecorddata());
				// 以下需要查表了解有那些数据
				sendHumi=Integer.parseInt(e.getString("humi"));
				sendTemp=Integer.parseInt(e.getString("temp"));
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("humi", sendHumi);
				map.put("temp", sendTemp);
				String jsonStr = JSON.toJSONString(map);
				PrintWriter out = response.getWriter();
				out.println(jsonStr);
				return;
			}
		}
		HttpSession session=request.getSession();
		String whereSql = "";
		String deviceForm = "<!-- 传感器面板实例 -->	<div class='col-md-6'>		<div class='panel panel-primary'>			<div class='panel-heading'>				<h3 class='panel-title text-center'>%s监控</h3>			</div>			<div class='panel-body'>				<div class='row'>					<div class='col-sm-5'>						<div class='form-group'>							<label>选择开始时间：</label>							<!--指定 date标记-->							<div class='input-group date' id='%s-dtp1'>								<input type='text' class='form-control' /> <span									class='input-group-addon'> <span									class='glyphicon glyphicon-calendar'></span>								</span>							</div>						</div>					</div>					<div class='col-sm-5'>						<div class='form-group'>							<label>选择结束时间：</label>							<!--指定 date标记-->							<div class='input-group date' id='%s-dtp2'>								<input type='text' class='form-control' /> <span									class='input-group-addon'> <span									class='glyphicon glyphicon-calendar'></span>								</span>							</div>						</div>					</div>					<div class='col-sm-2'>						<div class='form-group'>							<div class='btn-group-vertical'>								<button id='%s-rt' type='submit' class='btn btn-primary'>实时</button>								<button id='%s-que' type='submit' class='btn btn-default'>查询</button>							</div>						</div>					</div>				</div>				<div class='row'>					<div id='%s-chart'	style='min-width: 400px; height: 350px; margin: 0 auto;overflow:auto;'></div>				</div>			</div>		</div>	</div>";
		String controlForm = "<!-- 控制器面板实例 -->	<div class='col-md-6'>		<div class='panel panel-primary'>			<div class='panel-heading'>				<h3 class='panel-title text-center'>%s控制</h3>			</div>			<div class='panel-body'>				<div class='row'>					<div class='col-sm-5'>						<div class='form-group'>							<label>选择开始时间：</label>							<div class='input-group date' id='%s-dtp1'>								<input type='text' class='form-control' /> <span									class='input-group-addon'> <span									class='glyphicon glyphicon-calendar'></span>								</span>							</div>						</div>					</div>					<div class='col-sm-5'>						<div class='form-group'>							<label>选择结束时间：</label>							<div class='input-group date' id='%s-dtp2'>								<input type='text' class='form-control' /> <span									class='input-group-addon'> <span									class='glyphicon glyphicon-calendar'></span>								</span>							</div>						</div>					</div>					<div class='col-sm-2'>						<div class='form-group'>							<div class='btn-group-vertical'>								<button id='%s-rt' type='submit' class='btn btn-primary'>实时</button>								<button id='%s-que' type='submit' class='btn btn-default'>查询</button>							</div>						</div>					</div>				</div>				<div class='row'>					<div id='%s-chart'	style='min-width: 400px; height: 350px; margin: 0 auto;overflow:auto;'></div>				</div>			</div>		</div>	</div>";
		String newForm = "";
		List<ScriptNeedInfo> infoList = new ArrayList<ScriptNeedInfo>();
		if(request.getParameter("gid")!=null){
			List<String> newForms = new ArrayList<String>();
			Long gid = Long.parseLong(request.getParameter("gid"));
			// for 查询需要 Form名（独一无二）、Form代码、gdid
			System.out.println(gid);
			UtilsDao ud = new UtilsDao();
			List<Tgatedevice> queryTemps = ud.getGateDevicesByGid(gid);
			for(Tgatedevice queryTemp : queryTemps) {
				ScriptNeedInfo tmpInfo = new ScriptNeedInfo();
				String formName = queryTemp.getClientdeviceid();
				tmpInfo.setCode(formName);
				tmpInfo.setDescript(queryTemp.getClientdevicename());
				newForm = String.format(((ud.getDeviceTypeNameByDid(queryTemp.getDid()).equals("控制设备"))?controlForm:deviceForm),queryTemp.getClientdevicename(), formName,formName,formName,formName,formName);
				newForms.add(newForm);
				infoList.add(tmpInfo);
			}
			request.setAttribute("newForms", newForms);
			request.setAttribute("gid", gid); // 回传上传查询内容
			System.out.println("[infoList] "+infoList.size());
		}
		session.setAttribute("infoList", infoList);
		request.getRequestDispatcher("history.jsp").forward(request, response);
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
